<template>
    <el-dialog style="background: #F0F0F0;" :visible.sync="value" center :show-close="false" width="80%" top="8vh">
        <el-form ref="form" :model="single" label-position="right" label-width="80px">

            <el-row>
                <el-col :span="24">
                    <el-form-item prop="chapterId" label="所属章节" :rules="[{required:true,message:'请选择所属章节',trigger:'change'}]">
                        <el-cascader-panel  v-model="single.chapterId" :options="schoolList" :props="{emitPath:false,value:'id',label:'name',children:'children'}">
                            <template slot-scope="{ node, data }">
                                <span>{{ data.name }}</span>
                                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                            </template>
                        </el-cascader-panel>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item prop="sourced" label="试题来源" :rules="[{required:true,message:'请选择试题来源',trigger:'change'}]">
                        <el-radio-group v-model="single.sourced">
                            <el-radio label="1">课程试题</el-radio>
                            <el-radio label="2">面试宝典</el-radio>
                            <el-radio label="3">企业真题</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item prop="companyId" label="企业名称" :style="{'display':sourcedHiddenValue}" error="请选择企业" :required="(single.sourced && single.sourced.includes('3')) ? true : false">
                        <el-select v-model="single.companyId" clearable filterable style="margin-right:10px" placeholder="请选择企业">
                            <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in companyList"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="24">
                    <el-form-item prop="singleContent" label="试题题干" :rules="[{required:true,message:'请输入试题题干',trigger:'blur'}]">
                        <!--<el-input minlength="2" maxlength="300" show-word-limit type="textarea" v-model="single.singleContent" placeholder="请输入单选题题干"></el-input>-->
                        <quill-editor
                                ref="myQuillEditor"
                                class="editor"
                                v-model="single.singleContent"
                                :options="editorOptions">
                        </quill-editor>

                        <el-upload
                                class="avatar-uploader"
                                :action="url"
                                name="file"
                                :headers="{token:token()}"
                                :show-file-list="false"
                                :on-success="uploadSuccess"
                                :on-error="uploadError"
                                :before-upload="beforeUpload">
                        </el-upload>


                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="singleOptionA" label="选项A组" :rules="[{required:true,message:'请输入选项A',trigger:'blur'}]">
                        <el-input minlength="2" maxlength="300" show-word-limit type="text" v-model="single.singleOptionA" placeholder="请输入单选题选项A组"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="singleOptionB" label="选项B组" :rules="[{required:true,message:'请输入选项B',trigger:'blur'}]">
                        <el-input minlength="2" maxlength="300" show-word-limit type="text" v-model="single.singleOptionB" placeholder="请输入单选题选项B组"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="singleOptionC" label="选项C组" :rules="[{required:true,message:'请输入选项C',trigger:'blur'}]">
                        <el-input minlength="2" maxlength="300" show-word-limit type="text" v-model="single.singleOptionC" placeholder="请输入单选题选项C组"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="singleOptionD" label="选项D组" :rules="[{required:true,message:'请输入选项D',trigger:'blur'}]">
                        <el-input minlength="2" maxlength="300" show-word-limit type="text" v-model="single.singleOptionD" placeholder="请输入单选题选项D组"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="singleAsk" label="试题答案" :rules="[{required:true,message:'请选择试题答案',trigger:'change'}]">
                        <el-radio-group v-model="single.singleAsk">
                            <el-radio label="1">A</el-radio>
                            <el-radio label="2">B</el-radio>
                            <el-radio label="3">C</el-radio>
                            <el-radio label="4">D</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>

        </el-form>

        <template slot="footer">
            <el-button type="success" v-loading.fullscreen.lock="fullscreenLoading" @click="handleSubmit" icon="el-icon-plus">提交</el-button>
        </template>

    </el-dialog>
</template>

<script>

    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.snow.css'
    import 'quill/dist/quill.bubble.css'
    import { quillEditor } from 'vue-quill-editor'

    import { getChapterChildrenBySchool } from "@/api/academic/school";
    import { saveSingle } from "@/api/academic/single";
    import { getToken } from "@/utils/tool";

    const toolbarOptions = [
        ["bold"], // 加粗 斜体 下划线 删除线 "italic", "underline", "strike"
        ["blockquote", "code-block"], // 引用  代码块
        [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
        [{ indent: "-1" }, { indent: "+1" }], // 缩进
        [{ size: ["small", false, "large", "huge"] }], // 字体大小
        [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
        [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
        [{ font: [] }], // 字体种类
        [{ align: [] }], // 对齐方式
        ["clean"], // 清除文本格式
        ["link", "image", "video"] // 链接、图片、视频
    ];

    export default {
        name: "single-child",
        components:{
            quillEditor
        },
        data(){
            return {
                value : false,
                fullscreenLoading:false,
                single:{},
                schoolList:[],
                companyList:[
                    {id:'1',name:'张三的公司'},{id:'2',name:'李四的公司'}
                ],
                sourcedHiddenValue:"none",
                url:'http://47.97.77.138:56700/upload/image',
                quillUpdateImg:false, //根据图片上传状态来确定是否显示loading动画，刚开始是false
                editorOptions:{
                    placeholder:'你想写点什么呢？',
                    theme:'snow',//or 'bubble'
                    modules: {
                        toolbar:{
                            container:toolbarOptions,
                            handlers:{
                                'image':function(value){
                                    if(value){
                                        //触发input框选择图片文件
                                        document.querySelector(".avatar-uploader input").click();
                                    }else{
                                        this.quill.format("image",false);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        watch:{
            value(data){
                if(data){
                    getChapterChildrenBySchool().then(res=>{
                        this.schoolList = res.data.data;
                    })
                }
            },
            'single.sourced'(data){
                if(data && data == '3'){
                    this.sourcedHiddenValue = 'block';
                }else{
                    this.sourcedHiddenValue = 'none';
                }
            }
        },
        methods:{
            token(){
              return getToken();
            },
            beforeUpload(file){
                const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
                const isLt1M = file.size / 1024 / 1024 < 1;
                if (!isJPG) {
                    this.$message.error('支持JPG、PNG格式的图片，大小不得超过1M');
                }
                if (!isLt1M) {
                    this.$message.error('文件最大不得超过1M');
                }

                isJPG && isLt1M ? this.quillUpdateImg = true : this.quillUpdateImg = false;

                return isJPG && isLt1M;

            },
            uploadSuccess(res,file){
                //获取富文本实例
                let quill = this.$refs.myQuillEditor.quill;
                //如果上传成功
                if(res.success){
                    //获取光标所在位置
                    let length = quill.getSelection().index;
                    //插入图片
                    quill.insertEmbed(length,'image',res.data);
                    //调整光标到最后
                    quill.setSelection(length + 1);
                }else{
                    this.$message.error({message:'图片插入失败',center:true});
                }
                //loading动画消失
                this.quillUpdateImg = false;
            },
            uploadError(){
                //loading动画消失
                this.quillUpdateImg = false;
                this.$message.error({message:'图片插入失败',center:true});
            },
            handleSubmit(){
                this.$refs['form'].validate(valid=>{
                    if(valid){
                        this.single.type = '1';
                        this.fullscreenLoading = true;
                        saveSingle(this.single).then(res=> {
                            this.$message({
                                type: res.data.success ? 'success' : 'error',
                                message: res.data.message
                            });
                            this.value = false;
                            this.fullscreenLoading = false;
                            this.$parent.getSingleList(this.$parent.params);
                        });
                    }else{
                        return false;
                    }
                })
            }
        }
    }
</script>

<style scoped>

</style>